package cn.com.inossem.operation;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;

import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.com.inossem.config.WSConfig;
import cn.com.inossem.model.QueryProjectInfoBean;
import cn.com.inossem.model.QueryProjectOpportunityInfoBean;
import cn.com.inossem.network.NetworkConnect;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.Utils;

/**
 * 项目机会接口
 * 
 * @author szc
 */
public class JobsOpportunityOperation implements Operation {
	public static final String MESSAGE_OPERATION_JOBSBEAN = "message_operation_jobsbean";
	private static final String TAG = "MessageListOperation";

	@Override
	public Bundle execute(Context context, Request request)
			throws ConnectionException, DataException, CustomRequestException {
		Gson gson = new Gson();
		QueryProjectOpportunityInfoBean bean = (QueryProjectOpportunityInfoBean) request.getParcelable(MESSAGE_OPERATION_JOBSBEAN);
		String tojson = gson.toJson(bean).toString();
		System.out.println("tojson:" + tojson);
		NetworkConnect connection = null;
		if (Utils.isDenglu == 1) {
			connection = new NetworkConnect(WSConfig.LOCAL_URL
					+ "projectInfo/queryProjectInfo");
		} else {

			connection = new NetworkConnect(WSConfig.LOCAL_URL
					+ "projectInfo/unLoginProjectInfo");
		}
		connection.setPostText(tojson);

		String body = connection.execute();
		System.out.println("JobsOpportunityOperation:" + body);
		Bundle bundle = new Bundle();

		try {
			JSONObject jsonObject = new JSONObject(body);
			List<QueryProjectInfoBean> retList;
			int errorFlag = jsonObject.getInt("errorFlag");

			if (errorFlag == WSConfig.RESULT_SUCESS) // 成功
			{
				String jobslist = jsonObject.getString("queryProjectInfoList");

				// json转为带泛型的list
				retList = gson.fromJson(jobslist,
						new TypeToken<List<QueryProjectInfoBean>>() {
						}.getType());

			} else {
				retList = new ArrayList<QueryProjectInfoBean>();
			}
			// 返回项目机会
			bundle.putParcelableArrayList(
					WooRequestFactory.RESPONSE_JOBSOPPORTUNITY_DATA,
					(ArrayList<? extends Parcelable>) retList);

			// 设置登陆结果
			bundle.putInt(WooRequestFactory.BUNDLE_JOBSOPPORTUNITY_LIST, 1);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return bundle;
	}

}
